package com.jhhc.StormSurgeForecast.AstronomicalTide.Util;

import com.jhhc.Weathers.datasupplement.util.NC_util;
import ucar.nc2.Attribute;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;
import ucar.nc2.dataset.NetcdfDataset;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * @author LYQ
 * 风场文件工具类
 */
public class WindSiteUtil {
    private static final String ALGORITHM = "AES";
    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final TimeUtil timeUtil = new TimeUtil();
    /**
     * 获取最新的文件夹
     * @param localFile 存放数据文件的文件夹路径
     */
    public String getNewestTimeFile(String localFile){
        File file = new File(localFile);
        File[] files = file.listFiles();
        assert files != null;
        int newest = 0;
        long max = 0;
        long present = 0;
        for (int i = 0; i < files.length; i++) {
            present = files[i].lastModified();
            if (max < present) {
                max = present;
                newest = i;
            }
        }
        return files[newest].getPath();
    }

    public static String decrypt(String encryptedData, String key) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedData);
    }

    /**
     * 根据时间判断风场文件目录
     */
    public static String getWindPath(String time){
        TimeObject ts = timeUtil.currentTimes(time);
        String hour;
        if ("00".equals(ts.getHour()) || "12".equals(ts.getHour())) {
            hour = ts.getHour();
        }else {
            int h = Integer.parseInt(ts.getHour());
            if (h < 12) {
                hour = "00";//09
            }else {
                hour = "12";//21
            }
        }
        return ts.getYear() + ts.getMonth() + ts.getDay() + hour;
    }

    /**
     * 根据时间判断风场文件目录
     */
    public static String getWindPath1(String time){
        TimeObject ts = timeUtil.currentTimes(time);
        if ("09".equals(ts.getHour())){
            return ts.getYear() + ts.getMonth() + ts.getDay() + "00";
        } else if ("21".equals(ts.getHour())) {
            return ts.getYear() + ts.getMonth() + ts.getDay() + "12";
        }else {
            int h = Integer.parseInt(ts.getHour());
            if (h >= 9 && h < 21) {
                return ts.getYear() + ts.getMonth() + ts.getDay() + "00";
            } else if (h < 9) {
                ts = timeUtil.currentTimes(timeUtil.dateAddDay(time,-1));
                return ts.getYear() + ts.getMonth() + ts.getDay() + "12";
            }else {
                return ts.getYear() + ts.getMonth() + ts.getDay() + "12";
            }
        }
    }

    public static String getHeadInfo(String startTime,String endTime){
        return "spatial resolution:0.1" + "   startTime:" + startTime + "   endTime:" + endTime +
                "\r\n";
    }

    public static String readNc(String path,String region,String startTime,String endTime,String scPath){
        long startTime1 = System.currentTimeMillis();
        try {
            //获取
            String vPath = path + File.separator + "VGRD10m.nc";
            String uPath = path + File.separator + "UGRD10m.nc";
            String sPath = path + File.separator + "slp.nc";
            String[] strings = region.split(",");
            double startLat = Double.parseDouble(strings[1]);
            double endLat = Double.parseDouble(strings[3]);
            double startLon = Double.parseDouble(strings[0]);
            double endLon = Double.parseDouble(strings[2]);
            NetcdfFile netcdfFileV = NetcdfDataset.open(vPath);
            NetcdfFile netcdfFileU = NetcdfDataset.open(uPath);
            NetcdfFile netcdfFileS = NetcdfDataset.open(sPath);
            Variable variableV = netcdfFileV.findVariable("VGRD10m");
            Variable variableU = netcdfFileU.findVariable("UGRD10m");
            Variable variableS = netcdfFileS.findVariable("slp");
            Variable time = netcdfFileS.findVariable("time");//时间
            Variable lat = netcdfFileS.findVariable("lat");//纬度
            Variable lon = netcdfFileS.findVariable("lon");//经度
            float[] timeList = (float[]) time.read().copyTo1DJavaArray();//时间
            System.out.println("timeList:" + timeList.length);
            double[] latList = (double[]) lat.read().copyTo1DJavaArray();//纬度
            double[] lonList = (double[]) lon.read().copyTo1DJavaArray();//经度
            double[][][] v = (double[][][]) variableV.read().copyToNDJavaArray();
            double[][][] u = (double[][][]) variableU.read().copyToNDJavaArray();
            float[][][] s = (float[][][]) variableS.read().copyToNDJavaArray();
            List<Attribute> attributes = time.getAttributes();
            String tm = String.valueOf(attributes.get(2).getValues()).substring(12);
            netcdfFileV.close();
            netcdfFileU.close();
            netcdfFileS.close();

            StringBuilder s1 = new StringBuilder();
            String valueV,valueS,valueU;
            for (int i = 0; i < timeList.length; i++) {//时间
                String rtm = format.format(NC_util.dateAddyear(tm, (int) timeList[i]));
                System.out.println(rtm);
                if (timeUtil.compareTime(rtm,startTime) <= 0 && timeUtil.compareTime(rtm,endTime) >= 0) {
                    s1.append(rtm).append("\r\n");
                    for (int j = latList.length - 1; j >= 0; j--) {//纬度 大-小
                        if (latList[j] <= startLat && latList[j] >= endLat) {
                            for (int k = 0; k < lonList.length; k++) {//经度 小-大
                                if (lonList[k] >= startLon && lonList[k] <= endLon) {
                                    valueV = String.format("%E",v[i][j][k]);
                                    valueU = String.format("%E",u[i][j][k]);
                                    valueS = String.format("%.6f",s[i][j][k]);
                                    s1.append(Double.parseDouble(valueV) >= 0 ? "    " + valueV:"   " + valueV)
                                            .append(Double.parseDouble(valueU) >= 0 ? "    " + valueU:"   " + valueU)
                                            .append(Double.parseDouble(valueS) < 1000 ? "    " + valueS + "0":"    " + valueS)
                                            .append("\r\n");
                                }
                            }
                        }
                    }
                }
                createFile(scPath,s1.toString());
                s1 = new StringBuilder();
            }
            long endTime1 = System.currentTimeMillis();
            float excTime = (float)(endTime1 - startTime1) / 1000;
            System.out.println("解析生成风场文件耗时：" + excTime + "s");
            return s1.toString();
        } catch (IOException e) {
            e.printStackTrace();
            long endTime1 = System.currentTimeMillis();
            float excTime = (float)(endTime1 - startTime1) / 1000;
            System.out.println("文件解析异常耗时：" + excTime + "s");
            return null;
        }
    }
    public static String readNcXY(String path,String scPath,String region){
        long startTime1 = System.currentTimeMillis();
        try {
            String[] strings = region.split(",");
            double startLat = Double.parseDouble(strings[1]);
            double endLat = Double.parseDouble(strings[3]);
            double startLon = Double.parseDouble(strings[0]);
            double endLon = Double.parseDouble(strings[2]);
            NetcdfFile netcdfFileV = NetcdfDataset.open(path);
            Variable lat = netcdfFileV.findVariable("lat");//纬度
            Variable lon = netcdfFileV.findVariable("lon");//经度
            double[] latList = (double[]) lat.read().copyTo1DJavaArray();//纬度
            double[] lonList = (double[]) lon.read().copyTo1DJavaArray();//经度
            netcdfFileV.close();
            StringBuilder s1 = new StringBuilder();
            for (int j = latList.length - 1; j >= 0; j--) {//纬度 大-小
                if (latList[j] <= startLat && latList[j] >= endLat) {
                    for (int k = 0; k < lonList.length; k++) {//经度 小-大
                        if (lonList[k] >= startLon && lonList[k] <= endLon) {
                            s1.append(latList[j]).append(",").append(lonList[k]).append("\r\n");
                        }
                    }
                }
            }
            createFile(scPath,s1.toString());
            long endTime1 = System.currentTimeMillis();
            float excTime = (float)(endTime1 - startTime1) / 1000;
            System.out.println("解析生成风场文件耗时：" + excTime + "s");
            return s1.toString();
        } catch (IOException e) {
            e.printStackTrace();
            long endTime1 = System.currentTimeMillis();
            float excTime = (float)(endTime1 - startTime1) / 1000;
            System.out.println("文件解析异常耗时：" + excTime + "s");
            return null;
        }
    }
    /**
     * 生成文件
     */
    public static void createFile(String path,String value){
        FileOutputStream fos = null;
        try {
            File file = new File(path);
            fos = new FileOutputStream(file,true);
            byte[] sBytes = value.getBytes();
            fos.write(sBytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
